<template>
    <div class="flex_col_start w100 flex_grow" style="height: 100vh;">
        <label class="flex_center_self">{{ ctx.name }}</label>
        <div
            style="display: flex; flex-direction: row; width: 100%; align-items: start; justify-content: space-between; min-height: 0; flex-grow: 1;">
            <div class="flex_col_start" style="overflow-y: auto; height: 100%;">
                <FirmTypeItem v-for="(item, index) in ctx.firmTypes" :key="index" :firm-type="item"
                    @delete="onItemDelete(item)" @detail="onItemDetail(item)" />
            </div>
            <CreateFirmTypeParts :proj_id="ctx.proj_id" @created="onCreated" />
            <label></label>
        </div>
    </div>
</template>

<script lang="ts" setup>
import CreateFirmTypeParts from '@/components/CreateFirmTypeParts.vue';
import FirmTypeItem from '@/components/FirmTypeItem.vue';
import router from '@/router';
import { deleteFirmType, queryFirmType, type TbFirmType } from '@/service/firm_type';
import { runAction } from '@/utils/ui';
import { parseNumber } from '@/utils/utils';
import { reactive } from 'vue';
import { useRoute } from 'vue-router';


const route = useRoute();

interface Ctx {
    firmTypes: TbFirmType[],
    proj_id: number,
    name: string,
}

const ctx = reactive<Ctx>({
    firmTypes: [],
    proj_id: parseNumber(route.query.proj_id as string),
    name: route.query.name as string,
});

async function init() {
    const items = await queryFirmType(ctx.proj_id);
    ctx.firmTypes = items;
}

async function onCreated() {
    await runAction('更新', '', async () => {
        await init();
    });
}

async function onItemDelete(item: TbFirmType) {
    await runAction('删除', '', async () => {
        await deleteFirmType(item.id);
        await init();
    });
}

async function onItemDetail(item: TbFirmType) {
    await router.push({
        path: '/firm_file',
        query: {
            type_id: item.id,
            name: item.name,
        }
    });
}

init();

</script>
